﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Comet_sample.Models
{
    public class CometMessage
    {
        private Dictionary<String, CometAsyncResult> _clients = new Dictionary<String, CometAsyncResult>();

        private static readonly CometMessage _instance = new CometMessage();

        public static CometMessage GetInstance()
        {
            return _instance;
        }

        public void AddMessage(CometAsyncResult cometResult)
        {
            var content = cometResult.HttpContext.Request.Form["content"] ?? string.Empty;
            if (string.IsNullOrEmpty(content))
            {
                cometResult.SendMessage("empty");
                return;
            }

            if (content.Equals("connect", StringComparison.OrdinalIgnoreCase))
            {

                var cookie = cometResult.HttpContext.Request.Cookies["sid"];
                var cid = string.Empty;
                if (cookie != null)
                {
                    cid = cookie.Value;
                }

                if (string.IsNullOrEmpty(cid))
                {
                    cometResult.SendMessage(null);
                    return;
                }

                if (!_clients.ContainsKey(cid))
                {
                    _clients.Add(cid, cometResult);
                }
                
                return;
            }
            else
            {

                if (content.Equals("count", StringComparison.OrdinalIgnoreCase))
                {
                    cometResult.SendMessage(_clients.Count.ToString() + "人在线");
                    return;
                }

                var id = cometResult.HttpContext.Request.Cookies["sid"].Value;

                foreach (var item in _clients)
                {
                    item.Value.SendMessage("id: " + id + " send: " + content);
                }

                _clients.Clear();
            }
        }
    }
}